package rpc

import (
	"fmt"
	"net"
	"net/http"
	"net/rpc"
	"net/rpc/jsonrpc"
)

func HttpServer() {
	service := new(CalcService)
	rpc.Register(service)
	helloService := new(HelloService)
	rpc.Register(helloService)

	rpc.HandleHTTP()
	fmt.Println("start rpc server with http")

	err := http.ListenAndServe(":1234", nil)
	if err != nil {
		fmt.Println(err.Error())
		return
	}
}

func TcpServer() {
	calcService := new(CalcService)
	rpc.Register(calcService)
	helloService := new(HelloService)
	rpc.Register(helloService)

	tcpAddr, err := net.ResolveTCPAddr("tcp", ":1234")
	checkError(err)

	listener, err := net.ListenTCP("tcp", tcpAddr)
	checkError(err)

	for {
		conn, err := listener.Accept()
		if err != nil {
			fmt.Println(err.Error())
			continue
		}

		go rpc.ServeConn(conn)
	}
}

func JsonRpcServer() {
	calcService := new(CalcService)
	rpc.Register(calcService)
	helloService := new(HelloService)
	rpc.Register(helloService)

	tcpAddr, err := net.ResolveTCPAddr("tcp", ":1234")
	checkError(err)

	listener, err := net.ListenTCP("tcp", tcpAddr)
	checkError(err)
	for {
		conn, err := listener.Accept()
		if err != nil {
			fmt.Println(err.Error())
			continue
		}

		go jsonrpc.ServeConn(conn)
	}
}
